package com.mashen.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mashen.util.ConfigUtil;
import com.mashen.util.Constant;
import com.mashen.util.MessageUtil;
import com.mashen.util.SignUtil;
import com.mshen.service.WeixinService;
import com.mshen.service.model.OmitDumplicateMsg;
import com.mshen.service.model.WeixinRequest;
/**
 * Servlet implementation class WeiXinServlet
 */
 
public class WeiXinServlet extends  HttpServlet {
	private static final long serialVersionUID = 1L;
	private WeixinService service=new WeixinService();
    private OmitDumplicateMsg oltmsg=new OmitDumplicateMsg();
    public WeiXinServlet() {
        System.out.println("WeiXinServlet 被创建");
    }

	/**
	 *验证微信公众号开发者
	 *只有在微信官网填写服务器配置的时候被调用
	 */
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		 System.out.println("doGet start");
		 String signature=request.getParameter("signature");
		 String timestamp=request.getParameter("timestamp");
		 String nonce=request.getParameter("nonce");
		 String echostr=request.getParameter("echostr");
		 if(signature==null){
			 response.getWriter().write("参数错误");
		 }else if(SignUtil.validSign(signature, 
				 ConfigUtil.getValue("token"), 
				 timestamp, nonce)){
			 System.out.println("验证成功");
			 response.getWriter().write(echostr);
		 }else{
			 System.out.println("验证失败");
			 response.getWriter().write("fail");
		 }
		 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
		 HttpServletResponse response) throws ServletException, IOException {
		 System.out.println("doPost start");
		 try {
			WeixinRequest wxreq=MessageUtil.getWeixinRequest(request);
			//System.out.println(wxreq.getContent());
			String msgid=null;
			if(Constant.MSG_TYPE_EVENT
					.equals(wxreq.getMsgType())){//事件消息
				msgid=wxreq.getFromUserName()+wxreq.getCreateTime();
				
			}else{//普通消息
				msgid=wxreq.getMsgId();
			}
			//去重处理
			if(oltmsg.exist(msgid)){//如果重复发送消息则忽略
				response.getWriter().write("");
				return ;
			}
			oltmsg.set(msgid);			
			System.out.println("fromusername="+wxreq.getFromUserName());
			String respMsg=service.processMsg(wxreq);
			response.getWriter().write(respMsg);
		 } catch (Throwable e) {
			e.printStackTrace();
		}		 
	}

}
